#!/usr/bin/env python3
# sds module: https://github.com/ikalchev/py-sds011
# apt-get remove python3-serial
# pip3 install pyserial
import numpy as np
from serial import Serial
import os, time,socket,sys,json,random,sds011
from meas_data import meas_data

sensor="sds011"

pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"mean_count":2,"deviceid":"FF","ring_length":30,"wait":0.1,"cycle":20,"check_last":2,"gpg_keyid":"","usbport":"/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0","meascount":5,"meassleep":30,"digits":5,"store_dir":"/home/pi/log/","multiplicator":1000,"check_last_shrinking":0.9}
for n in parameter:
	if n in log_conf:
		parameter[n]=log_conf[n]
parameter["sensor"]="SDS011"

bsds=False
if sensor in log_conf:
	bsds=True
	for n in parameter:
		if n in log_conf[sensor]:
			parameter[n]=log_conf[sensor][n]
	try:
		sensor=sds011.SDS011(parameter['usbport'],use_query_mode=True)
	except:
		bsds=False
	else:
		bpm25=False
		bpm10=False
		par25=parameter
		par25["var_name"]="pm25"
		pm25=meas_data(par25)
		par10=parameter
		par10["var_name"]="pm10"
		pm10=meas_data(par10)

		bmqtt=False
		if "mqtt" in log_conf:
			bmqtt=True
			lcmq=log_conf['mqtt']
			mbroker=""
			if 'broker' in lcmq:
				mbroker=lcmq['broker']
			else:
				bmqtt=False
			mport=1883
			if 'port' in lcmq:
				mport=lcmq['port']
			if bmqtt:
				pm25.set_mqtt(broker=mbroker,port=mport)
				pm10.set_mqtt(broker=mbroker,port=mport)

a = 2

if bsds:
	while True:
		sensor.sleep(sleep=False)
		for i in range(parameter['meascount']):
			(data25,data10)=sensor.query()
			pm25.append(data25)
			pm10.append(data10)
		sensor.sleep()
		time.sleep(60*parameter['meassleep'])


# close the client

print("done")


